package com.example.lifecycleserviceusage

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Observer

/**
 * https://zhuanlan.zhihu.com/p/75974735
 * launchMode: SingleInstance 保证前台服务不会多次创建MainActivity实例
 */
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val btn = findViewById<Button>(R.id.start_service_btn)
        btn.setOnClickListener {
            Intent(this@MainActivity, MyLifecycleService::class.java).also {
                startService(it)
            }
            // todo: 前台服务没效果
            Intent(this@MainActivity, MyForegroundService::class.java).also {
                startService(it)
            }

        }
        val bindBtn = findViewById<Button>(R.id.bind_service_btn)
        bindBtn.setOnClickListener {
            val serviceConnection = object : ServiceConnection {
                override fun onServiceConnected(
                    name: ComponentName?,
                    service: IBinder?
                ) {
                    (service as MyLifecycleService.MyBinder).service
                        .numberLiveData.observe(this@MainActivity, Observer {
                            bindBtn.text = "哈哈哈回调成功"
                            // 这里更新UI，比如把service里边的livedata设置到textview
                        })
                }

                override fun onServiceDisconnected(name: ComponentName?) {
                }
            }
            // 绑定服务，把Service看作一个服务器,Activity为客户端
            Intent(this@MainActivity, MyLifecycleService::class.java).also {
                bindService(it, serviceConnection, BIND_AUTO_CREATE)
            }
        }
    }
}